import React, { FC } from 'react';
import { Transforms, Element as SlateElement } from 'slate';
import { useSlateStatic, ReactEditor } from 'slate-react';

import { WebsiteElement, RenderElementPropsAttributes } from '../slate';
import { defaultWebsite } from '../share';

interface UrlInputProps {
  url: string;
  onChange: (url: string) => void;
}

const UrlInput: FC<UrlInputProps> = ({ url, onChange }) => {
  const [value, setValue] = React.useState(url);
  return (
    <input
      value={value}
      onClick={(e) => e.stopPropagation()}
      style={{
        marginTop: '5px',
        boxSizing: 'border-box',
        width: '100%',
      }}
      onChange={(e) => {
        const newUrl = e.target.value;
        setValue(newUrl);
        onChange(newUrl);
      }}
    />
  );
};

interface WebsiteProps {
  attributes: RenderElementPropsAttributes;
  element: WebsiteElement;
}

export const Website: FC<WebsiteProps> = ({ attributes, children, element }) => {
  const editor = useSlateStatic();
  const { url } = element;
  return (
    <div {...attributes}>
      <div
        contentEditable={false}
        style={{
          width: 'min-content',
        }}
      >
        <iframe
          src={`${url || defaultWebsite}?title=0&byline=0&portrait=0`}
          frameBorder="0"
          style={{
            border: 'black solid 1px',
          }}
        />
        <UrlInput
          url={url || defaultWebsite}
          onChange={(val) => {
            const path = ReactEditor.findPath(editor, element);
            const newProperties: Partial<SlateElement> = {
              url: val,
            };
            Transforms.setNodes(editor, newProperties, { at: path });
          }}
        />
      </div>
      {children}
    </div>
  );
};
